import { AfterViewInit, Component, EventEmitter, Input, OnInit, Output, Renderer2 } from '@angular/core';
import { ApesMessageService } from '@shared/apes/message';
import { ApiService } from '@core/services/http/api.service';
import { isNotNil } from '@shared/apes/core/util/check';
import { FormGroup } from '@angular/forms';
import { AddPanelComponent } from './addPanel/addPanel.component';
import { UserAuthService } from '@core/services/user-auth.service';

export type editorType = 'add' | 'edit' | 'del' | 'copy';

@Component({
  selector: 'admin-panel',
  templateUrl: './adminPanel.component.html',
})


export class AdminPanelComponent implements OnInit, AfterViewInit {

  params: any;

  ctx = { model: {} };

  data = [
    { api: 'aut.post.findAll', name: '岗位权限' },
    { api: 'aut.user.findAll', name: '个人权限' },
  ];

  form: FormGroup;

  // 用户信息
  userBody:any;

  allCanvas: any = []; // 全部看板

  // 面板主体
  panelBody :any;


  constructor(private renderer: Renderer2,
              private msg: ApesMessageService,
              private panelService: AddPanelComponent,
              protected userService: UserAuthService,
              private apiService: ApiService) {
  }

  ngOnInit() {
    this.initUser();
    this.initPanel();
    this.form = new FormGroup({});
  }

  ngAfterViewInit() {
  }

  // 按钮层
  onEvent(data: editorType, index?: any) {
    this.editorPanel(data, index);
  }

  // 初始化用户信息
  initUser() {
    this.userBody = {
      userId : null,
      postId : null,
      post : [],
      user : []
    };
    this.userService.getUser().subscribe(user => {
      console.log(user);
      let data = {'name': user['name'], 'id': user['id']};
      this.userBody.userId = user['id'];
      this.userBody.postId = user['post'].id;
      this.userBody.post.push(user['post']);
      this.userBody.user.push(data);
    });
  }

  // 初始化面板
  initPanel() {
    this.panelBody = {
      title: null,
      btn: '确定',
      editor: null,
      context: {
        // id: null, // 唯一ID
        // name: null, // 面板名称
        // description: null, // 描述
        // post: [], // 岗位权限
        // user: [], // 个人权限
        // className: 'layout-aa',
      },
    };
    let data = {'postId':this.userBody.postId,'userId':this.userBody.userId};
    // bi.canvas.findAllForAuth
    this.apiService.post('bi.canvas.findAllForAuth', data).subscribe(body => {
      if (body && isNotNil(body) && body.length > 0) {
        // console.log(body);
        // this.allCanvas = body.content;
        this.allCanvas = body;
      }
    });
  }

  // 编辑面板
  editorPanel(state, index) {
    let data = this.allCanvas[index];
    let body = this.panelBody;
    // 删除面板
    if (state == 'del') {
      this.apiService.post('bi.canvas.delete', this.allCanvas[index]).subscribe(body => {
        this.msg.error(body);
        this.initPanel();
      });
    } else {
      // 创建面板
      if (state == 'add') {
        body['title'] = '创建面板';
        body['btn'] = '创建';
        body['editor'] = 'add';
        body['context'].className = 'layout-aa';
        body['context']['post'] = this.userBody['post'];
        body['context']['user'] = this.userBody['user'];
      }
      // 编辑面板 && 复制面板
      else if (state == 'edit' || state == 'copy') {
        data.post = [];
        data.user = [];
        body['context'] = data;
        // 编辑面板
        if (state == 'edit') {
          body['title'] = '编辑面板';
          body['editor'] = 'edit';
        }
        // 复制面板
        if (state == 'copy') {
          body['title'] = '复制面板';
          body['editor'] = 'copy';
          body['context'].id = null;
        }

        if(data['canvasPostPermits']){
          data['canvasPostPermits'].forEach((res) => {
            body['context'].post.push(res['post']);
          });
        }
        if(data['canvasUserPermits']){
          data['canvasUserPermits'].forEach((res) => {
            body['context'].user.push(res['user']);
          });
        }
      }

      this.panelService.openDialog(body, () => {
        this.initPanel();
      });
    }
  }

  @Output() curCanvas = new EventEmitter<any[]>();

  // 跳转当前面板
  showPanel(index){
    this.curCanvas.emit(this.allCanvas[index]);
  }

}
